/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/itframe">itframe</a> All rights reserved.
 */
package com.rise.itframe.modules.inv.web;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.rise.itframe.common.config.Global;
import com.rise.itframe.common.persistence.Page;
import com.rise.itframe.common.utils.Collections3;
import com.rise.itframe.common.utils.excel.ExportExcel;
import com.rise.itframe.common.web.BaseController;
import com.rise.itframe.modules.inv.entity.InvConf;
import com.rise.itframe.modules.inv.entity.InvInfo;
import com.rise.itframe.modules.inv.service.InvConfService;
import com.rise.itframe.modules.inv.service.InvInfoService;
import com.rise.itframe.modules.sys.entity.Dict;
import com.rise.itframe.modules.sys.utils.DictUtils;
import com.rise.itframe.modules.sys.utils.UserUtils;

/**
 * 发票登记信息Controller
 * 
 * @author ming
 * @version 2017-12-31
 */
@Controller
@RequestMapping(value = "${adminPath}/inv/invInfo")
public class InvInfoController extends BaseController {

	@Autowired
	private InvInfoService invInfoService;
	@Autowired
	private InvConfService invConfService;

	@ModelAttribute
	public InvInfo get(@RequestParam(required = false) String id) {
		InvInfo entity = null;
		if (org.apache.commons.lang3.StringUtils.isNotBlank(id)) {
			entity = invInfoService.get(id);
		}
		if (entity == null) {
			entity = new InvInfo();
		}
		return entity;
	}

	// @RequiresPermissions("inv:invInfo:view")
	@RequestMapping(value = { "list", "" })
	public String list(InvInfo invInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (request.getSession().getAttribute("invType") != null && !"9".equals(invInfo.getOperateFlag())) {
			invInfo.setInvType((String) request.getSession().getAttribute("invType"));
		}
		Page<InvInfo> page = invInfoService.findPage(new Page<InvInfo>(request, response), invInfo);
		model.addAttribute("page", page);

		if ("9".equals(invInfo.getOperateFlag())) {// 查询统计
			Map<String, String> sumMap = invInfoService.findListSum(invInfo);
			model.addAttribute("sumMap", sumMap);
			return "modules/inv/invInfoSearchList";
		}
		return "modules/inv/invInfoList";
	}

	/**
	 * 查询相似的开票列表
	 * 
	 * @param invInfo
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "findSimilarList")
	public String findSimilarList(InvInfo invInfo, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		List<InvInfo> list = invInfoService.findSimilarList(invInfo);
		model.addAttribute("list", list);

		return "modules/inv/invInfoSimilarList";
	}

	/**
	 * 查询相似的开票列表
	 * 
	 * @param invInfo
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "findSimilarListSize")
	@ResponseBody
	public String findSimilarListSize(InvInfo invInfo, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		invInfo.setOperateFlag("1");
		List<InvInfo> list = invInfoService.findSimilarList(invInfo);
		return String.valueOf(list.size());
	}

	@RequestMapping(value = "getAllInvDeptNames")
	@ResponseBody
	public List<String> getAllInvDeptNames(InvInfo invInfo, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		return invInfoService.getAllInvDeptNames(invInfo);
	}

	// @RequiresPermissions("inv:invInfo:view")
	@RequestMapping(value = "form")
	public String form(InvInfo invInfo, HttpServletRequest request, Model model) {
		if (invInfo.getInvType() != null) {
			request.getSession().setAttribute("invType", invInfo.getInvType());
		} else {
			invInfo.setInvType((String) request.getSession().getAttribute("invType"));
		}

		if (invInfo.getIsNewRecord()) {
			invInfo.setStatus("0");
			invInfo.setCreateBy(UserUtils.getUser());
			invInfo.setCreateDate(new Date());
			invInfo.setInvDate(new Date());
		}
		model.addAttribute("invInfo", invInfo);
		return "modules/inv/invInfoForm";
	}

	// @RequiresPermissions("inv:invInfo:edit")
	@RequestMapping(value = "save")
	public String save(InvInfo invInfo, Model model, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		if (org.apache.commons.lang3.StringUtils.isBlank(invInfo.getInvType())) {
			invInfo.setInvType((String) request.getSession().getAttribute("invType"));
		}
		if (!beanValidator(model, invInfo)) {
			return form(invInfo, request, model);
		}
		invInfoService.save(invInfo);
		addMessage(redirectAttributes, "保存发票登记信息成功");
		if ("9".equals(invInfo.getOperateFlag())) {// 保存
			model.addAttribute("rtnCode", "0");
			return form(invInfo, request, model);
		} else {
			return "redirect:" + Global.getAdminPath() + "/inv/invInfo/form?operateFlag=1&invType="
					+ invInfo.getInvType();
		}
	}

	/**
	 * ajax校验发票单位和开票次数
	 * 
	 * @param invInfo
	 * @param model
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "validator")
	@ResponseBody
	public String validator(InvInfo invInfo, Model model, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		// 校验发票名称是否正确
		List<InvInfo> list;
		invInfo.setCurrentUser(UserUtils.getUser());
		if ("5".equals(invInfo.getInvType())) {// 同一车牌号打车日期相近的不能再次录入打车日期加减7
			// 打车相近日期从数据字典中获取，默认为7
			Integer plateNoInterval = 7;
			List<Dict> dictList = DictUtils.getDictList("INV_PLATE_INTERVAL");
			if (!Collections3.isEmpty(dictList)) {
				plateNoInterval = Integer.parseInt(dictList.get(0).getValue());
			}
			
			list = invInfoService.findListByPlateNo(invInfo,plateNoInterval);
			if (!list.isEmpty()) {
				return "该车牌号的打车日期相近"+plateNoInterval+"天内";
			}
		} else {
			// 餐费白名单不校验此项
			boolean flag = false;
			if ("2".equals(invInfo.getInvType())) {// 交通发票同一天统一开票单位不能录入，加入到白名单的单位不验证
				InvConf conf = invConfService.getByInvDeptName(invInfo.getInvDeptName());
				if (conf != null) {
					flag = true;
				}
			}
			if (!flag) {
				list = invInfoService.findListByDept(invInfo);
				if (!list.isEmpty()) {
					return "该发票与经办人为" + list.get(0).getTransactName() + "的发票同一天同一开票单位";
				}
			}

			list = invInfoService.findListByTransact(invInfo);
			if (!list.isEmpty()) {
				return "该发票的经办人今天已有发票录入记录";
			}
			InvInfo cond = new InvInfo();
			cond.setInvCode(invInfo.getInvCode());
			cond.setOperateFlag("99");
			list = invInfoService.findList(cond);
			if (!list.isEmpty() && !list.get(0).getId().equals(invInfo.getId())) {
				return "开票编号已存在";
			}

			invInfo.setOperateFlag("1");
			list = invInfoService.findSimilarList(invInfo);
			if (!list.isEmpty()) {
				return "该发票编号与经办人" + list.get(0).getTransactName() + "的相近";
			}

			InvConf conf = invConfService.getByInvDeptName(invInfo.getInvDeptName());
			// 查询当天用户开发次数
			if (conf != null && invInfoService.getInvNums(invInfo) >= conf.getInvNum()) {
				return "开票单位“" + invInfo.getInvDeptName() + "”,最大开票次数为" + conf.getInvNum();
			}
		}
		return "success";
	}

	// @RequiresPermissions("inv:invInfo:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(InvInfo invInfo, RedirectAttributes redirectAttributes) {
		invInfoService.delete(invInfo);
		return "success";
	}

	/**
	 * 导出查询列表
	 *
	 * @param dttColorPrintFileInfo
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "export", method = RequestMethod.POST)
	@ResponseBody
	public String exportExcel(InvInfo invInfo, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) throws IOException {
		try {
			Page<InvInfo> page = invInfoService.findPage(new Page<InvInfo>(request, response, -1), invInfo);
			model.addAttribute("page", page);

			Map<String, String> sumMap = invInfoService.findListSum(invInfo);
			model.addAttribute("sumMap", sumMap);

			List<String> headerList = Lists.newArrayList();
			headerList.add("开票单位/车牌号");
			headerList.add("发票编号");
			headerList.add("报销类型");
			headerList.add("开票金额");
			headerList.add("开票日期");
			headerList.add("开票类型");
			headerList.add("经办人");
			headerList.add("录入人");
			headerList.add("录入时间");

			ExportExcel ee = new ExportExcel("发票信息", headerList);
			int index = 0;
			for (int i = 0; i < page.getList().size(); i++) {
				index = 0;
				Row row = ee.addRow();
				InvInfo data = page.getList().get(i);
				ee.addCell(row, index++, data.getInvDeptName());
				ee.addCell(row, index++, data.getInvCode());
				ee.addCell(row, index++,
						DictUtils.getDictLabel(data.getClaimType(), "INV_CLAIM_TYPE", data.getClaimType()));
				ee.addCell(row, index++, data.getAmout());
				ee.addCell(row, index++, data.getInvDate());
				ee.addCell(row, index++, DictUtils.getDictLabel(data.getInvType(), "INV_TYPE", ""));
				ee.addCell(row, index++, data.getTransactName());
				ee.addCell(row, index++, data.getCreateBy().getName());
				ee.addCell(row, index++, data.getCreateDate());
			}

			index = 0;
			Row row = ee.addRow();
			ee.addCell(row, index++, "汇总");
			ee.addCell(row, index++, "");
			ee.addCell(row, index++, "");
			ee.addCell(row, index++, sumMap.get("AMOUT"));
			ee.addCell(row, index++, "");
			ee.addCell(row, index++, "");
			ee.addCell(row, index++, "");
			ee.addCell(row, index++, "");
			ee.addCell(row, index++, "");
			ee.write(response, "发票信息导出" + new Date().getTime() + ".xlsx");
			return null;

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("导出失败！");
		}
		return null;
	}

}